#ifndef __LCM_IOUTILS_H__
#define __LCM_IOUTILS_H__

#include <stdio.h>
#include <inttypes.h>
#include <wininet.h>
#include <winsock2.h>

#define BSP_LITTLE_ENDIAN 1

#if BSP_LITTLE_ENDIAN
    /*-----------------------------------------------------------------*/
    /* Change byte order so the least significant byte is stored at    */
    /* the lowest address. Unsigned to prevent integer overflow on     */
    /* i960. Big endian cast unsigned for constant handling of vars.   */
    /*-----------------------------------------------------------------*/
    #define htonl(addr)     ( (((ULONG)(addr) & 0x000000FF)<<24) | \
                             (((ULONG)(addr) & 0x0000FF00)<<8)  | \
                             (((ULONG)(addr) & 0x00FF0000)>>8)  | \
                             (((ULONG)(addr) & 0xFF000000)>>24))
 
    #define ntohl(addr)     htonl(addr)
 
    #define htons(addr)     ( (((USHORT)(addr) & 0x000000FF)<<8)  | \
                             (((USHORT)(addr) & 0x0000FF00)>>8))
 
    #define ntohs(addr)     htons(addr)
#else

    #define htonl(a)       ((ULONG)(a))
    #define ntohl(a)       ((ULONG)(a))
    #define htons(a)       ((USHORT)(a))
    #define ntohs(a)       ((USHORT)(a))
#endif

static inline int fwrite32(FILE *f, int32_t v)
{
    v = htonl(v);
    if (fwrite(&v, 4, 1, f) == 1) return 0; else return -1;
}

static inline int fwrite64(FILE *f, int64_t v64)
{
    int32_t v = v64>>32;
    if (0 != fwrite32(f, v)) return -1;
    v = v64 & 0xffffffff;
    return fwrite32(f, v);
}

static inline int fread32(FILE *f, int32_t *v32)
{
    int32_t v;

    if (fread(&v, 4, 1, f) != 1)
        return -1;

    *v32 = ntohl(v);

    return 0;
}

static inline int fread64(FILE *f, int64_t *v64)
{
    int32_t v1, v2;

    if (fread32(f, &v1))
        return -1;

    if (fread32(f, &v2))
        return -1;

    *v64 =     (((int64_t) v1)<<32) | (((int64_t) v2)&0xffffffff);

    return 0;
}

#endif
